<template>
  <div>
    <div style="margin-bottom: 10px;position: relative;">
      <a-form-model :model="model" ref="form" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="生产单位" style="margin-bottom: 0" prop="productDepartment">
              <j-search-select-tag
                v-model="model.productionDepart"
                :dict-options="departmentOptions"
                @change="handleAllSelectChange(arguments, 'productionDepart')"
              ></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产线" style="margin-bottom: 0" prop="productionLine">
              <j-dict-select-tag
                v-model="model.productionLine"
                dict-code="hf_production_line"
                @change="handleAllSelectChange(arguments, 'productionLine')"
              ></j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="班次" style="margin-bottom: 0" prop="workShift">
              <j-dict-select-tag
                v-model="model.workShift"
                dict-code="hf_work_shift"
                :filter-options="['3']"
                @change="handleAllSelectChange(arguments, 'workShift')"
              ></j-dict-select-tag>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div style="position: absolute;right: 0;top: 0">
        <a-space>
          <a-button type="primary" v-if="!editable" @click="editAll()">编辑</a-button>
          <a-button
            type="primary"
            :style="{ backgroundColor: saveColor, borderColor: saveColor }"
            v-else
            @click="saveAll()"
            >保存</a-button
          >
        </a-space>
      </div>
    </div>
    <a-table
      ref="table"
      size="small"
      bordered
      :columns="columns"
      :dataSource="dataSource"
      :loading="loading"
      :rowKey="record => record.materialCode"
      :pagination="false"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template slot="productionDepart" slot-scope="text, record">
        <j-search-select-tag
          style="width: 100%"
          v-model:value="record.productionDepart"
          :dict-options="departmentOptions"
          v-show="editable"
          @change="handleSelectChange(arguments, record, 'productionDepart')"
        ></j-search-select-tag>
        <span v-show="!editable">{{ record.productionDepart_dictText }}</span>
      </template>

      <template slot="productionLine" slot-scope="text, record">
        <j-dict-select-tag
          style="width: 80px"
          v-model:value="record.productionLine"
          dict-code="hf_production_line"
          v-show="editable"
          @change="handleSelectChange(arguments, record, 'productionLine')"
        ></j-dict-select-tag>
        <span v-show="!editable">{{ record.productionLine_dictText }}</span>
      </template>

      <template slot="workShift" slot-scope="text, record">
        <j-dict-select-tag
          style="width: 80px"
          v-model:value="record.workShift"
          dict-code="hf_work_shift"
          v-show="editable"
          @change="handleSelectChange(arguments, record, 'workShift')"
        ></j-dict-select-tag>
        <span v-show="!editable">{{ record.workShift_dictText }}</span>
      </template>

      <template slot="planProduceNumber" slot-scope="text, record">
        <a-input-number
          v-model:value="record.planProduceNumber"
          v-show="editable"
          :min="0"
          @keydown.enter="closeInput($event, record)"
        ></a-input-number>
        <span v-show="!editable" @dblclick="handleClick($event, record)">{{ text }}</span>
      </template>
    </a-table>
  </div>
</template>

<script>
import { getAction, postAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteColor, saveColor } from '@/defaultSettings'

export default {
  name: 'GenerateProductOrderEntry',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '',
      width: 1200,
      visible: false,
      queryParam: {},
      model: {
        productionDepart: '',
        productionLine: '',
        workShift: ''
      },
      disableMixinCreated: true,
      /* 排序参数 */
      isorter: {
        column: 'materialCode',
        order: 'asc'
      },
      /* table加载状态 */
      loading: false,
      editable: false,
      columns: [
        {
          title: '工序',
          align: 'center',
          dataIndex: 'stepId_dictText'
        },
        {
          title: '生产单位',
          align: 'center',
          dataIndex: 'productionDepart_dictText',
          scopedSlots: { customRender: 'productionDepart' }
        },
        {
          title: '产线',
          align: 'center',
          dataIndex: 'productionLine',
          scopedSlots: { customRender: 'productionLine' }
        },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'workShift',
          scopedSlots: { customRender: 'workShift' }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '计划生产总数',
          align: 'center',
          dataIndex: 'planProduceNumber',
          scopedSlots: { customRender: 'planProduceNumber' }
        },
        {
          title: '收料仓库',
          align: 'center',
          dataIndex: 'warehouse_dictText'
        }
      ],

      confirmLoading: false,
      validatorRules: {},
      url: {
        generateProductOrder: '/production/hfProductOrder/generateProductOrder',
        list: '/material/hfBom/generateProductInputPreview'
      },
      departmentOptions: []
    }
  },
  created() {
    // this.initDictData();
  },
  methods: {
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.id.split(','), [record])
          }
        }
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleValid() {
      // 产线、班次、生产单位必填校验
      const requiredFields = ['productionLine', 'workShift', 'productionDepart']
      const valid = this.dataSource.every((item, index) => {
        let flag = true
        for (const fieldName of requiredFields) {
          if (!item[fieldName]) {
            flag = false
          }
        }
        return flag
      })
      if (!valid) {
        this.$message.error('产线,班次,生产单位没有填写完整')
        return false
      }
      return true
    },
    handleOk() {
      this.confirmLoading = true
      postAction(this.url.generateProductOrder, this.dataSource)
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    loadData1(data) {
      this.dataSource = data
    },
    editAll() {
      this.editable = true
    },
    saveAll() {
      this.editable = false
    },
    initDictData() {
      getAction('/sys/sysDepart/queryByParentId', { parentDepartName: '制造课' }).then(res => {
        if (res.success) {
          this.departmentOptions = res.result.map(item => {
            return {
              label: item.departName,
              value: item.id,
              text: item.departName
            }
          })
        }
      })
    },
    handleSelectChange([value, text], record, fieldName) {
      const newData = [...this.dataSource]
      const target = newData.find(item => item.materialCode === record.materialCode)
      if (target) {
        target[fieldName] = value
        target[fieldName + '_dictText'] = text
      }
      this.dataSource = newData
    },
    handleAllSelectChange([value, text], fieldName) {
      const newData = [...this.dataSource]
      newData.forEach(i => {
        i[fieldName] = value
        i[fieldName + '_dictText'] = text
      })
      this.dataSource = newData
    },
    handleClick(e, record) {
      e.preventDefault()
      const newData = [...this.dataSource]
      const target = newData.find(item => item.materialCode === record.materialCode)
      if (target) {
        target.selectable = true
      }
      this.dataSource = newData
    },
    closeInput(e, record) {
      e.preventDefault()
      const newData = [...this.dataSource]
      const target = newData.find(item => item.materialCode === record.materialCode)
      if (target) {
        target.selectable = false
      }
      this.dataSource = newData
    }
  }
}
</script>

<style scoped></style>
